package com.cx.base.rx;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * 去重function
 */
public class DeduplicationFunction<T> implements Function<List<T>, List<T>> {
    private final Set<T> mDepot = new HashSet<>();


    public void clean() {
        mDepot.clear();
    }


    @Override
    public List<T> apply(@NonNull List<T> ts) throws Exception {
        List<T> result = new ArrayList<>();
        Iterator<T> iterator = ts.iterator();
        while (iterator.hasNext()) {
            T next = iterator.next();
            boolean contains = mDepot.contains(next);
            if (!contains)
                result.add(next);
            mDepot.add(next);
        }
        return result;
    }
}
